<?php

namespace App\Http\Controllers\PartTime;

use App\Facades\Style;
use App\Facades\Site;
use App\Http\Controllers\Controller;
use App\Http\Requests\PartTime\PartTimeCreateRequest;
use App\Models\Common\CollTown;
use App\Models\Common\CollArea;
use App\Models\Common\WebConfig;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyUser;
use App\Models\Company\CrmService;
use App\Models\PartTime\PartTimeJobs;
use App\Models\PartTime\PartTimeJobsFreeTime;
use App\Models\PartTime\PartTimeResume;
use App\Models\PartTime\PartTimeSignProcess;
use App\Models\PartTime\PartTimeSignUp;
use App\Models\Personal\Resume;
use Illuminate\Http\Request;
use Auth;



/**
 * 兼职招聘
 * Class RecruitController
 * @package App\Http\Controllers\PartTimePosition
 */
class RecruitController extends Controller
{
    private $uid = '';//用户id
    private $com_id = '';//公司id
    private $userInfo = [];//用户信息

    /**
     * 获取公司基本信息
     */
    private function getBasicInfo()
    {
        $userInfo = Auth::guard('company')->user();
        $this->userInfo = $userInfo;
        $this->uid = $userInfo->uid;
        $companyBasic = CompanyBasic::where('uid', $userInfo->uid)->orderBy('updatetime', 'desc')->firstOrFail(['id']);
        $this->com_id = $companyBasic->id;
    }

    /**
     * 后台兼职管首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        //定义激活的标签
        $active = 'pt_index';
        $this->getBasicInfo();
        $endTime = date('Y-m-d H:i:s');
        $startTime = date('Y-m-d H:i:s', time() - 10 * 24 * 60 * 60);
        $count = PartTimeSignUp::where('company_uid', '=', $this->uid)
            ->where('com_id', $this->com_id)
            ->whereBetween('created_at', [$startTime, $endTime])
            ->whereIn('status', [2, 3])//定义“2同意邀约”和“3已被婉拒”为全部，排除“1查看”，“4删除”两者都排除
            ->count();
        if ($count == 0) {
            $percentageProcessed = 100;
        } else {
            $total = PartTimeSignUp::where('company_uid', '=', $this->uid)
                ->where('com_id', $this->com_id)
                ->whereBetween('created_at', [$startTime, $endTime])
                ->whereIn('status', [0, 1, 2, 3])//定义“0待处理”、“1已查看、“2同意邀约”和“3已被婉拒”为全部，排除“1查看”，“4删除”两者都排除
                ->count();
            if ($total == 0) {
                $percentageProcessed = 100;
            } else {
                $percentageProcessed = round($count / $total * 100);
            }
        }
        //查询客服人员
        $ServiceSql = CrmService::select('uid','sex', 'worker_name', 'weichat', 'qq', 'img', 'enounce', 'mobile');

        if(!empty($this->userInfo->crm_uid)){
            $CrmService = $ServiceSql->where('uid', $this->userInfo->crm_uid)->first();//提取客服信息
        }else{
            $CrmService = $ServiceSql->where('uid', Site::get('DefaultCompanyService'))->first();
        }

        if(empty($CrmService)) $CrmService= new CrmService();
        //照片
        if(!empty(Site::get('CrmHttpAdress'))){
            if(!empty($CrmService->img)){
                $CrmService->img = Site::get('CrmHttpAdress') .'/upload/worker/'. $CrmService->img;
            }else{
                $CrmService->img = asset('default/images/company/headpic.jpg') ;
            }
        }else{
            if(!empty($CrmService->img)){
                $CrmService->img = asset('/upload/worker/'.$CrmService->img);
            }else{
                $CrmService->img = asset('default/images/company/headpic.jpg') ;
            }
        }
        //电话
        if(empty($CrmService->mobile)){
            $CrmService->mobile = Site::get('DefaultCompanyServiceMobile');
        }
        //QQ
        if(empty($CrmService->qq)){
            $CrmService->qq = Site::get('DefaultCompanyServiceQQ');
        }
        //微信
        if(empty($CrmService->weichat)){
            $CrmService->weichat = Site::get('DefaultCompanyServiceWeiChat');
        }
        //个人宣言
        if(empty($CrmService->enounce)){
            $CrmService->enounce = trim(Site::get('DefaultCompanyServiceEnounce'));
        }else{
            $CrmService->enounce = trim($CrmService->enounce);
        }
        return Style::view('part_time.company.index', compact('active', 'percentageProcessed', 'CrmService'));
    }

    /**
     * 首页刷新全部兼职
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function refreshAll()
    {
        $this->getBasicInfo();
        $list = PartTimeJobs::where('uid', '=', $this->uid)
            ->where('com_id', $this->com_id)
            ->whereIn('job_status', [0, 1, 2])
            ->get(['id', 'updated_at']);
        if ($list->count() > 0) {
            foreach ($list as $k => $v) {
                $input['updated_at'] = date('Y-m-d H:i:s');
                $v->update($input);
            }
            return back()->with('msg', '刷新成功');
        }
        if ($list->count() == 0) {
            return back()->with('msg', '您还没有创建兼职职位');
        }
        return response('错误代码!', 404);
    }

    /**
     * 报名管理页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function signUp(Request $request)
    {
        //定义激活的标签
        $active = 'pt_sign_up';
        $this->getBasicInfo();
        $status = $request->status ? (int)$request->status : 0;
        $list = PartTimeSignUp::has('signUpResume')
            ->with('signUpResume')
            ->where('company_uid', '=', $this->uid)
            ->whereIn('status', [0, 1, 2, 3])
            ->where('com_id', $this->com_id)
            ->where(function ($query) use ($status) {
                if ($status >= 0) {
                    $query->where('status', $status);//筛选状态
                }
            })->paginate(10);
        $filter = ['status' => $status];
        return Style::view('part_time.company.sign_up', compact('list', 'filter', 'active'));
    }

    /**
     * 更改报名记录状态
     * @param Request $request
     * @return $this|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function signStatus(Request $request)
    {
        $this->getBasicInfo();
        $statusArr = [1, 2, 3];
        if (in_array($request->status, $statusArr)) {
            $status = $request->status;
        } else {
            return response('系统错误!', 404);
        }
        $id = $request->selected_id;
        $count = count($id);
        $list = PartTimeSignUp::where('company_uid', '=', $this->uid)
            ->where('com_id', $this->com_id)
            ->whereIn('status', [0, 1, 2, 3])
            ->whereIn('id', $id)
            ->get();
        if ($list->count() == $count) {
            switch ($status) {
                case '1':
                    $msg = '录用成功';
                    foreach ($list as $k => $v) {
                        $input['status'] = 1;
                        $v->update($input);
                        $this->signUpProcess($v, 1);
                    }
                    break;
                case '2':
                    $msg = '婉拒成功';
                    foreach ($list as $k => $v) {
                        $input['status'] = 2;
                        $v->update($input);
                    }
                    break;
                case '3':
                    $msg = '删除成功';
                    foreach ($list as $k => $v) {
                        $input['status'] = 3;
                        $v->update($input);
                    }
                    break;
            }
            return back()->with('msg', $msg);
        }
        return response('错误代码!', 404);
    }

    /**
     * 企业查看兼职简历
     * @param Request $request
     * @return mixed
     */
    public function viewResume(Request $request)
    {
        //定义激活的标签
        $active = 'pt_sign_up';
        $this->getBasicInfo();
        $id = $request->id;
        //找报名记录
        $signInfo = PartTimeSignUp::where('id', '=', $id)
            ->where('company_uid', '=', $this->uid)
            ->whereIn('status', [0, 1, 2, 3])
            ->where('com_id', $this->com_id)->firstOrFail(['pt_resume_id', 'personal_uid']);
        $signInfo->update(['status' => 1]);
        //找简历详情
        $info = PartTimeResume::where('uid', '=', $signInfo->personal_uid)->where('id', '=', $signInfo->pt_resume_id)->firstOrFail();
        //找头像
        $resume = Resume::where('uid', $signInfo->personal_uid)->where('default', '1')->first(['avatar']);
        $info->avatar = !empty($resume->avatar) ? asset('upload/personalavatar/' . $resume->avatar) : asset('default/images/personal/headPortrait.jpg');
        return Style::view('part_time.company.resume', compact('info', 'active'));
    }

    /**
     * 兼职管理页面
     * @return mixed
     */
    public function manage()
    {
        //定义激活的标签
        $active = 'pt_manage';
        $this->getBasicInfo();
        //查询列表
        $list = PartTimeJobs::where('uid', '=', $this->uid)
            ->where('com_id', $this->com_id)
            ->whereIn('job_status', [0, 1, 2])
            ->orderBy('updated_at', 'desc')
            ->paginate(10);
        return Style::view('part_time.company.manage', compact('list', 'active'));
    }

    /**
     * 企业预览兼职详情
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(Request $request)
    {
        //查询省市区信息
        $areaList = CollArea::getComplete();
        $id = $request->id;
        //查询信息
        $info = PartTimeJobs::where('id', '=', $id)
            ->whereIn('job_status', [0, 1, 2])
            ->firstOrFail();
        //app端信息
        $app['person_ios'] = WebConfig::getConfig('appPersonHasIOS');
        $app['person_android'] = WebConfig::getConfig('appPersonHasAndroid');
        $app['company_ios'] = WebConfig::getConfig('appCompanyHasIOS');
        $app['company_android'] = WebConfig::getConfig('appCompanyHasAndroid');
        //查询当前所属省市区信息
        $nowArea = CollArea::getAreaAddress($info->city_id);
        $companyInfo = CompanyBasic::where('id', $info->com_id)->first(['profile']);
        return Style::view('part_time.index.show', compact('info', 'companyInfo', 'areaList', 'nowArea', 'app'));
    }

    /**
     * 删除兼职
     * @param Request $request
     * @return $this|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function delete(Request $request)
    {
        $this->getBasicInfo();
        if ($request->isMethod('post')) {
            $id = $request->selected_id;
        } else {
            $id = $request->id;
            $id = [$id];
        }
        $count = count($id);
        $list = PartTimeJobs::where('uid', '=', $this->uid)
            ->where('com_id', $this->com_id)
            ->whereIn('job_status', [0, 1, 2])
            ->whereIn('id', $id)
            ->get(['id']);
        if ($list->count() == $count) {
            foreach ($list as $k => $v) {
                $v->timestamps = false;
                $input['job_status'] = 4;
                $v->update($input);
            }
            return back()->with('msg', '删除成功');
        }
        return response('错误代码!', 404);
    }

    /**
     * 激活/屏蔽兼职
     * @param Request $request
     * @return $this|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function changeStatus(Request $request)
    {
        $this->getBasicInfo();
        $statusArr = [1, 2];
        if (in_array($request->job_status, $statusArr)) {
            $job_status = $request->job_status;
        } else {
            return response('系统错误!', 404);
        }
        $id = $request->id;
        $info = PartTimeJobs::where('id', '=', $id)
            ->where('uid', '=', $this->uid)
            ->where('com_id', '=', $this->com_id)
            ->whereIn('job_status', [0, 1, 2])
            ->firstOrFail();
        if (!empty($info)) {
            $info->timestamps = false;
            $input['job_status'] = $job_status;
            $info->update($input);
            switch ($job_status) {
                case 1;
                    $msg = '激活成功';
                    break;
                case 2;
                    $msg = '屏蔽成功';
                    break;
            }
            return back()->with('msg', $msg);
        }
        return response('错误代码!', 404);
    }

    /**
     * 刷新兼职
     * @param Request $request
     * @return $this|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function refresh(Request $request)
    {
        $this->getBasicInfo();
        $id = $request->selected_id;
        $count = count($id);
        $list = PartTimeJobs::where('uid', '=', $this->uid)
            ->where('com_id', $this->com_id)
            ->whereIn('job_status', [0, 1, 2])
            ->whereIn('id', $id)
            ->get(['id', 'updated_at']);
        if ($list->count() == $count) {
            foreach ($list as $k => $v) {
                $input['updated_at'] = date('Y-m-d H:i:s');
                $v->update($input);
            }
            return back()->with('msg', '刷新成功');
        }
        return response('错误代码!', 404);
    }

    /**
     * 新建兼职页面
     * @return mixed
     */
    public function create()
    {
        //定义激活的标签
        $active = 'pt_manage';
        $this->getBasicInfo();
        $webAreaCode = WebConfig::getConfig('webareacode');
        if (strlen($webAreaCode) > 6 ) {
            $webAreaName = CollTown::getTownName($webAreaCode);
        } else {
            $webAreaName = CollArea::getAreaName($webAreaCode);
        }
        //搜索上条兼职信息
        $lastInfo = PartTimeJobs::where('uid', '=', $this->uid)
            ->whereIn('job_status', [0, 1, 2])
            ->where('com_id', $this->com_id)
            ->orderBy('updated_at', 'desc')
            ->first(['address', 'contacts', 'mobile', 'phone']);
        //找不到上条兼职信息找企业基本信息
        if (empty($lastInfo)) {
            $lastInfo = CompanyBasic::where('uid', $this->uid)->orderBy('updatetime', 'desc')->first(['address', 'contacts', 'mobile', 'phone']);
        }
        return Style::view('part_time.company.create', compact('lastInfo', 'webAreaCode', 'webAreaName', 'active'));
    }

    /**
     * 新建兼职操作
     * @param PartTimeCreateRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(PartTimeCreateRequest $request)
    {
        $this->getBasicInfo();
        $partTimeArray = $request->only('title', 'type_id', 'long_term', 'need_num', 'sex', 'education', 'salary_price', 'salary_unit', 'salary_method', 'city_id', 'address', 'longitude', 'latitude', 'coordinate_address', 'content', 'contacts', 'mobile');
        $partTimeArray['time_start'] = $request->input('time_start', '');//防止为空出现的错误
        $partTimeArray['time_end'] = $request->input('time_end', '');//防止为空出现的错误
        $phone = trim($request->input('area_code')) . '-' . trim($request->input('phone'));
        $phone .= trim($request->input('ext')) ? '-' . trim($request->input('ext')) : '';
        $partTimeArray['phone'] = trim($phone, '-');
        $partTimeArray['uid'] = $this->uid;
        $partTimeArray['com_id'] = $this->com_id;
        $partTimeArray['job_status'] = 0;
        $FreeTimeArray = $request->only('num');
        foreach ($FreeTimeArray['num'] as $key => $value) {
            $partTimeFreeTimeArray['num'.$key] = $value;
        }
        $partTimeJobsResult = PartTimeJobs::create($partTimeArray);
        if (empty($partTimeJobsResult->id)) {
            return back()->with('msg', '添加失败，请重试');
        }
        $partTimeFreeTimeArray['bt_id'] = $partTimeJobsResult->id;
        $partTimeJobsFreeTimeResult = PartTimeJobsFreeTime::create($partTimeFreeTimeArray);
        if ($partTimeJobsFreeTimeResult->id > 0) {
            return redirect(url('company/pt_manage'))->with('msg', '添加成功');
        } else {
            return back()->with('msg', '添加失败，请重试');
        }
    }

    /**
     * 兼职编辑页面
     * @param Request $request
     * @return mixed
     */
    public function edit(Request $request)
    {
        //定义激活的标签
        $active = 'pt_manage';
        $this->getBasicInfo();
        $id = $request->id;
        $info = PartTimeJobs::where('id', '=', $id)
            ->where('uid', '=', $this->uid)
            ->where('com_id', '=', $this->com_id)
            ->whereIn('job_status', [0, 1, 2])
            ->firstOrFail();
        if (strlen($info->city_id) > 6 ) {
            $info->webAreaName = CollTown::getTownName($info->city_id);
        } else {
            $info->webAreaName = CollArea::getAreaName($info->city_id);
        }
        return Style::view('part_time.company.edit', compact('info', 'active'));
    }

    /**
     * 更新兼职操作
     * @param PartTimeCreateRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(PartTimeCreateRequest $request)
    {
        $this->getBasicInfo();
        $id = $request->id;
        $partTimeArray = $request->only('title', 'type_id', 'long_term', 'need_num', 'sex', 'education', 'salary_price', 'salary_unit', 'salary_method', 'city_id', 'address', 'longitude', 'latitude', 'coordinate_address', 'content', 'contacts', 'mobile');
        $partTimeArray['time_start'] = $request->input('time_start', '');//防止为空出现的错误
        $partTimeArray['time_end'] = $request->input('time_end', '');//防止为空出现的错误
        $phone = trim($request->input('area_code')) . '-' . trim($request->input('phone'));
        $phone .= trim($request->input('ext')) ? '-' . trim($request->input('ext')) : '';
        $partTimeArray['phone'] = trim($phone, '-');
        $partTimeArray['job_status'] = 0;
        $freeTimeArray = $request->only('num');
        foreach ($freeTimeArray['num'] as $key => $value) {
            $partTimeFreeTimeArray['num'.$key] = $value;
        }
        $partTimeJobsResult = PartTimeJobs::where('id', '=', $id)
            ->where('uid', '=', $this->uid)
            ->where('com_id', '=', $this->com_id)
            ->whereIn('job_status', [0, 1, 2])
            ->update($partTimeArray);
        if ($partTimeJobsResult === false) {
            return back()->with('msg', '添加失败，请重试');
        }
        $partTimeJobsFreeTimeResult = PartTimeJobsFreeTime::where('bt_id', '=', $id)->update($partTimeFreeTimeArray);
        if ($partTimeJobsFreeTimeResult !== false) {
            return redirect(url('company/pt_manage'))->with('msg', '修改成功');
        } else {
            return back()->with('msg', '修改失败，请重试');
        }
    }

    /**
     * 添加报名处理记录
     * @param $info
     */
    private function signUpProcess($info, $status)
    {
        $data['company_uid'] = $info->company_uid;
        $data['com_id'] = $info->com_id;
        $data['personal_uid'] = $info->personal_uid;
        $data['pt_resume_id'] = $info->pt_resume_id;
        $data['pt_job_id'] = $info->pt_job_id;
        $data['status'] = $status;
        PartTimeSignProcess::create($data);
    }
}